// 此处可以import api
// import { GET_USERINFO_API } from '@/api/common';
// import router from '@/router/routes';
/* ======================================================================
 * 此store主要控制用户信息相关
 ======================================================================*/
import { menus } from '@/moke/menus-mock';
const user = {
  state: {
    userName: '',
    userCode: '',
    permissions: [],
    menus: [],
    openId: ''
  },
  mutations: {
    SET_USERNAME: (state, userName) => {
      state.userName = userName;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_MENU: (state, allMenu) => {
      state.menus = allMenu;
    },
    SET_USERCODE: (state, userCode) => {
      state.userCode = userCode;
    },
    SET_OPENID: (state, openId) => {
      state.openId = openId;
    }
  },

  actions: {
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_PERMISSIONS', []);
        resolve('退出成功');
      });
    },
    ActionUser({ commit, state }) {
      return new Promise((resolve, reject) => {
        // GET_USERINFO_API().then(response => {
        //   if (response.status) {
        // const _data = response.result;
        const _data = {
          userName: '波波',
          permissions: ['test_permissions'],
          userCode: '2743',
          menus,
          openId: 'dsads5415445d5sa41d5sa45ds1a45'
        };
        console.log('请求用户接口成功');
        commit('SET_USERNAME', _data.userName);
        commit('SET_USERCODE', _data.userCode);
        commit('SET_OPENID', _data.openId);
        commit('SET_PERMISSIONS', _data.permissions);

        commit('SET_MENU', _data.menus);// 后端返回菜单直接展示，不管前端路由

        // const routerNames = [];
        // router.options.routes.filter(n => n.children).forEach(val => val.children.forEach(n => routerNames.push(n.meta.label)));
        // const showMenus = function (arr) {
        //   const newArr = arr.filter(val => {
        //     if (val.children.length) {
        //       const childrenMenus = val.children.filter(v => {
        //         showMenus(val.children);
        //         return routerNames.findIndex(n => n === v.menuName) !== -1;
        //       });
        //       val.children = childrenMenus;
        //       return !!childrenMenus.length;
        //     } else {
        //       return routerNames.findIndex(n => n === val.menuName) !== -1;
        //     }
        //   });
        //   return newArr;
        // };
        // commit('SET_MENU', showMenus(_data.allMenu));// 后端返回菜单跟路由比对下，存在路由才展示对应的菜单
        resolve(_data);
        //   } else {
        //     resolve('error');
        //   }
        // }).catch(error => {
        //   reject(error);
        // });
      });
    }
  },
  getters: {
    getPermissions: state => {
      return state.permissions;
    },
    getUserInfo: state => {
      return state;
    }
  }
};
export default user;
